import Vue from 'vue'
import VueRouter from 'vue-router'
import { getUserRole, hasPermission } from '@/config/permission'
import { Message } from 'element-ui'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/user/login'
  },
  {
    path: '/user/login',
    name: 'login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/user/register',
    name: 'register',
    component: () => import('@/views/Register.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/user/forget',
    name: 'forget',
    component: () => import('@/views/Forget.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/dashboard',
    name: 'home',
    component: () => import('@/views/Home.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { requiresAuth: true }
      },
      // 用户管理路由
      {
        path: '/users',
        name: 'users',
        component: () => import('@/views/users/Index.vue'),
        meta: { requiresAuth: true, roles: ['admin'] },
        children: [
          {
            path: 'list',
            name: 'userList',
            component: () => import('@/views/users/UserList.vue'),
            meta: { requiresAuth: true, roles: ['admin'] }
          },
          {
            path: 'roles',
            name: 'userRoles',
            component: () => import('@/views/users/UserRoles.vue'),
            meta: { requiresAuth: true, roles: ['admin'] }
          }
        ]
      },
      // 商品管理路由
      {
        path: '/products',
        name: 'products',
        component: () => import('@/views/products/Index.vue'),
        meta: { requiresAuth: true },
        children: [
          {
            path: 'list',
            name: 'productList',
            component: () => import('@/views/products/ProductList.vue'),
            meta: { requiresAuth: true }
          },
          {
            path: 'category',
            name: 'productCategory',
            component: () => import('@/views/products/ProductCategory.vue'),
            meta: { requiresAuth: true }
          }
        ]
      },
      // 销售管理路由
      {
        path: '/sales',
        name: 'sales',
        component: () => import('@/views/sales/Index.vue'),
        meta: { requiresAuth: true },
        children: [
          {
            path: 'orders',
            name: 'orderList',
            component: () => import('@/views/sales/OrderList.vue'),
            meta: { requiresAuth: true }
          },
          {
            path: 'analysis',
            name: 'salesAnalysis',
            component: () => import('@/views/sales/SalesAnalysis.vue'),
            meta: { requiresAuth: true }
          }
        ]
      },
      // 库存管理路由
      {
        path: '/inventory',
        name: 'inventory',
        component: () => import('@/views/inventory/Index.vue'),
        meta: { requiresAuth: true },
        children: [
          {
            path: 'stock',
            name: 'inventoryStatus',
            component: () => import('@/views/inventory/InventoryStatus.vue'),
            meta: { requiresAuth: true, title: '库存状态' }
          },
          {
            path: 'in',
            name: 'inboundManagement',
            component: () => import('@/views/inventory/InboundManagement.vue'),
            meta: { requiresAuth: true }
          },
          {
            path: 'out',
            name: 'outboundManagement',
            component: () => import('@/views/inventory/OutboundManagement.vue'),
            meta: { requiresAuth: true }
          },
          {
            path: 'alert',
            name: 'inventoryAlerts',
            component: () => import('@/views/inventory/InventoryAlerts.vue'),
            meta: { requiresAuth: true }
          },
          {
            path: 'adjustment',
            name: 'storageView',
            component: () => import('@/views/inventory/StorageView.vue'),
            meta: { requiresAuth: true, roles: ['admin', 'user'], title: '库存操作' }
          }
        ]
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'hash',  // 使用 hash 模式
  base: process.env.BASE_URL,
  routes
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const whiteList = ['/user/login', '/user/register', '/user/forget']

  // 如果是访问登录或注册页面，直接放行
  if (whiteList.includes(to.path)) {
    next()
    return
  }

  // 没有token时，重定向到登录页
  if (!token) {
    next('/user/login')
    return
  }

  // 有token的情况下，进行权限验证
  const userRole = getUserRole()
  
  if (to.meta.roles && !to.meta.roles.includes(userRole)) {
    Message({
      message: '您没有权限访问该页面',
      type: 'error',
      duration: 3000
    })
    next('/user/login')
    return
  }

  if (!hasPermission(userRole, to)) {
    Message({
      message: '您没有权限访问该页面',
      type: 'error',
      duration: 3000
    })
    next('/user/login')
    return
  }

  next()
})

export default router 